package main

import (
	"bufio"
	"fmt"
	"net"
	// "time"
	"os"
)

const bufferSize = 2048

// GOOS=linux GOARCH=amd64 go build -o udp_client udp_client.go
// GOOS=windows GOARCH=amd64 go build -o udp_client_x64.exe udp_client.go
func main() {
	defer func(){ fmt.Scanln()}()
	fmt.Println("=== udp client tool (v1.0.0) ===")
	var serverIP,serverPort string
	if len(os.Args) == 3 {
		serverIP = os.Args[1]
		serverPort = os.Args[2]
	}else{
		fmt.Println("Command: ", "udp_client <target_ip> <target_port>")
		fmt.Println("Example: ", "udp_client 127.0.0.1 5002")
		fmt.Println();

		fmt.Println("Please enter the target ip(default 127.0.0.1):")
		fmt.Scanf("%s\n",&serverIP)
		if serverIP=="" { serverIP="127.0.0.1" }

		fmt.Println("Please enter the target port:")
		fmt.Scanf("%s\n",&serverPort)
		if serverPort == "" {
			fmt.Println("=> ServerPort error")
			return 
		}
	}
	fmt.Println()
	serverAddr, err := net.ResolveUDPAddr("udp", serverIP+":"+serverPort)
	if err != nil {
		fmt.Println("=> ResolveUDPAddr failed:", err)
		return
	}


	sockFd, err := net.DialUDP("udp", nil, serverAddr)
	if err != nil {
		fmt.Println("=> Create socket failed:", err)
		return
	}
	defer sockFd.Close()
	// sockFd.SetReadDeadline(time.Now().Add( 5 * time.Second))

	go func(){
		buffer := make([]byte, bufferSize)
		for{
			n, addr, err := sockFd.ReadFromUDP(buffer)
			if err != nil {
				fmt.Println("=> Receive message failed:", err)
				continue
			}
			fmt.Printf("Response from %s: %s\n", addr, string(buffer[:n]))
		}
	}()

	reader := bufio.NewReader(os.Stdin)
	for {
		fmt.Print("Enter message: ")
		     message, err := reader.ReadString('\n')
		if err != nil{
			fmt.Println("input error")
			continue
		}

		message = message[:len(message)-2]
		fmt.Println([]byte(message))
		_, err = sockFd.Write([]byte(message))
		if err != nil {
			fmt.Println("=> Send message failed:", err)
			continue
		}

		// buffer := make([]byte, bufferSize)
		// n, addr, err := sockFd.ReadFromUDP(buffer)
		// if err != nil {
		// 	fmt.Println("=> Receive message failed:", err)
		// 	continue
		// }
		// fmt.Printf("Response from %s: %s\n", addr, string(buffer[:n]))
	}
}
